﻿namespace gui {
    using System.Collections.ObjectModel;
    using snat.model;
    using System.Collections.Generic;
    using System.ComponentModel;
    using gui.Utils;
    using System;

    /// <summary>
    /// The Node List UI component of the Node Properties Tab
    /// </summary>
    public partial class NodeListView {

        private ObservableCollection<NodeItem> nodesList;
        public ObservableCollection<NodeItem> NodesList {
            get { return nodesList; }
        }

        public static event guiNodeListSelectionEvent NodeSelectedEvent;
        private static ClusterNode selectedNode;
        public static ClusterNode SelectedNode {
            get { return selectedNode; }
        }

        private static NodeListView instance;
        public static NodeListView Instance {
            get {
                if (instance == null) instance = new NodeListView();
                return instance;
            }
        }

        public NodeListView() {
            InitializeComponent();

            nodesList = new ObservableCollection<NodeItem>();
            foreach (ClusterNode n in NetworkModel.Instance.Nodes.Values) nodesList.Add(new NodeItem(n));

            // Create dispatching list for cross-thread binding
            DispatchingList<ObservableCollection<NodeItem>, NodeItem> dispatchingList = new DispatchingList<ObservableCollection<NodeItem>, NodeItem>(NodesList, Dispatcher);
            NodesListXAML.ItemsSource = dispatchingList;

            // Listen for new nodes added
            NetworkModel.Instance.NodeAdded += guiOnNodeAdded;
        }

        private void addToNodesList(NodeItem n) {
            if(!nodesList.Contains(n)) nodesList.Add(n);
        }

        public void guiOnNodeAdded(int id, BaseNode n) {
            addToNodesList(new NodeItem(n as ClusterNode));
        }

        private void NodesListXAML_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
            try {
                // On node list selection changed, update the display with its properties
                selectedNode = (NodesListXAML.SelectedItem as NodeItem).Node;
                NodeStatsInfo.PopulateWithNode(selectedNode);

                // Fire new node selected event
                if (NodeSelectedEvent != null) NodeSelectedEvent();

            } catch (NullReferenceException ex) { /*ignore exception and do nothing*/ } 
        }
    }
}